package com.yang.controller;

import com.aliyuncs.exceptions.ClientException;
import com.yang.AliyunSmsUtils;
import com.yang.Seriver.UserService;
import com.yang.entity.Result;
import com.yang.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * @Classname RegisterController
 * @Description TODO
 * @Date 2020/11/11 19:15
 * @Created by yang
 */
@RestController
@RequestMapping("/user")
public class RegisterController {
    @Autowired
    UserService userService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    HttpSession session;

    /**
     *@创建人  yang
     *@描述 校验学号 防止注册重复账号
     */
    @PostMapping("/register")
    public Result register(@RequestBody User user) {
        Object CodeRedis = redisTemplate.opsForValue().get("code");

        User byNumber = userService.findByNumber(user.getNumber());
        if (byNumber!=null || user.getCode()==null){
            return new Result(false,"学号已存在 请勿重复注册!");
        }
        if (CodeRedis==null){
            return new Result(false,"验证码已过期");
        }
        if (user.getCode().equals(CodeRedis.toString())){
            userService.save(user);
        }else {
            return new Result(false,"验证码错误！");
        }
        return new Result(true, "注册成功");
    }

   /**
    *@创建人  yang
    *@描述 手机发送短信
    */
    @PostMapping("/sendsms/{phone}")
    public Result sendsms(@PathVariable("phone") String phone ) throws ClientException {
        AliyunSmsUtils aliyunSmsUtils = new AliyunSmsUtils();
        aliyunSmsUtils.setNewcode();
        String code = Integer.toString(aliyunSmsUtils.getNewcode());
        aliyunSmsUtils.sendSms(phone,code);
        redisTemplate.opsForValue().set("code",code);
        return new Result(true,"短信发送成功");
    }
}
